﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows.Forms;
using System.Web;

namespace BugClient
{
    public partial class CreateForm : Form
    {
        WebClient web;
        string url;
        string sessionID;
        string productID;
        List<string> userList = new List<string>();
        string token;

        public CreateForm(WebClient web, string url, string sessionID, string productID, string productName, string[] users, Dictionary<string, string> userDict, string token)
        {
            InitializeComponent();

            Text = "创建-" + productName;
            this.web = web;
            this.url = url;
            this.sessionID = sessionID;
            this.productID = productID;
            this.token = token;
            userList.AddRange(users);
            foreach (var user in userList)
            {
                assignBox.Items.Add(userDict[user]);
            }
            priorityBox.SelectedIndex = 1;
        }

        private async void commitButton_Click(object sender, EventArgs e)
        {
            if (web.IsBusy)
                return;
            if (string.IsNullOrEmpty(titleBox.Text))
            {
                MessageBox.Show("标题不能为空");
                return;
            }
            if (assignBox.SelectedIndex < 0)
            {
                MessageBox.Show("请选择指派目标");
                return;
            }
            string response;
            try
            {
                string contentText;
                contentBox.SelectAll();
                if ((contentBox.SelectionType & RichTextBoxSelectionTypes.Object) == 0
                    && (contentBox.SelectionType & RichTextBoxSelectionTypes.MultiObject) == 0)
                    contentText = contentBox.Text;
                else
                    contentText = contentBox.Rtf;
                response = await web.UploadStringTaskAsync(url + "/create", string.Format("project={0}&title={1}&content={2}&assign={3}&priority={4}&token={5}", productID, HttpUtility.UrlEncode(titleBox.Text), HttpUtility.UrlEncode(contentText), userList[assignBox.SelectedIndex], priorityBox.SelectedItem, token));
            }
            catch (WebException ex)
            {
                MessageBox.Show("连接服务器失败：" + ex.Message);
                return;
            }
            if (string.IsNullOrEmpty(response))
            {
                MessageBox.Show("提交Bug失败");
                return;
            }
            DialogResult = DialogResult.OK;
            Dispose();
            Close();
        }
    }
}
